<?php

namespace app\admin\controller\parts;

use Throwable;
use app\common\controller\Backend;

/**
 * 库存审批管理
 */
class Approval extends Backend
{
    /**
     * Approval模型对象
     * @var object
     * @phpstan-var \app\admin\model\parts\Approval
     */
    protected object $model;

    protected array $withJoinTable = ['admin'];

    protected array|string $preExcludeFields = ['admin_id', 'create_time'];

    protected string|array $quickSearchField = ['id'];

    public function initialize(): void
    {
        parent::initialize();
        $this->model = new \app\admin\model\parts\Approval;
    }

    /**
     * 查看
     * @throws Throwable
     */
    public function index(): void
    {
        // 如果是 select 则转发到 select 方法，若未重写该方法，其实还是继续执行 index
        if ($this->request->param('select')) {
            $this->select();
        }

        /**
         * 1. withJoin 不可使用 alias 方法设置表别名，别名将自动使用关联模型名称（小写下划线命名规则）
         * 2. 以下的别名设置了主表别名，同时便于拼接查询参数等
         * 3. paginate 数据集可使用链式操作 each(function($item, $key) {}) 遍历处理
         */
        list($where, $alias, $limit, $order) = $this->queryBuilder();
        $res = $this->model
            ->withJoin($this->withJoinTable, $this->withJoinType)
            ->alias($alias)
            ->where($where)
            ->order($order)
            ->paginate($limit);
        $res->visible(['admin' => ['username']]);

        $this->success('', [
            'list'   => $res->items(),
            'total'  => $res->total(),
            'remark' => get_route_remark(),
        ]);
    }
    /**
     * 审核
     * @param int $id  记录ID
     * @param int $type 操作类型
     * @param int $approval_type 审批类型
     * @throws Throwable
     */
    public function Approval(int $id,int $type,int $approval_type): void
    {
        $row = $this->model->find($id);
        $Json = json_decode($row['old_json'],true);
        $NewJson = json_decode($row['new_json'],true);
        $obj_id = $Json['id'];
        if($type == 1){
            if($approval_type == 1 or $approval_type == 3)
            {
                // 1和3 是删除
                if($this->model->DeleteRecord($approval_type,$obj_id)){
                    $this->success("审核完成，记录已删除！");
                }else{
                    $this->error("操作失败！");
                }
                if($approval_type == 1 )
                {
                    $this->model = new \app\admin\model\parts\Info;
                }
                if($approval_type == 3 )
                {
                    $this->model = new \app\admin\model\parts\Entry();
                }
            }
            if($approval_type == 2 or $approval_type == 0)
            {
                //2和4 是编辑
                if($approval_type == 0 )
                {
                    $this->model = new \app\admin\model\parts\Info;
                }
                if($approval_type == 2 )
                {
                    $this->model = new \app\admin\model\parts\Entry();
                }
                $pk = "id";
                $NewJson['is_approval'] = 0;
                $this->EditInfo($NewJson,$pk,$obj_id);
            }
        }
        $row['approval_status'] = $type;
        $result = $row->save();
        if ($result !== false) {
            $this->success(__('Update successful'));
        } else {
            $this->error(__('No rows updated'));
        }
    }
    public  function EditInfo($NewJson,$pk,$obj_id){
        $row = $this->model->find($obj_id);
        $data = $this->excludeFields($NewJson);
        $result = false;
        $this->model->startTrans();
        try {
            // 模型验证
            if ($this->modelValidate) {
                $validate = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                if (class_exists($validate)) {
                    $validate = new $validate;
                    if ($this->modelSceneValidate) $validate->scene('edit');
                    $data[$pk] = $row[$pk];
                    $validate->check($data);
                }
            }
            $result = $row->save($data);
            $this->model->commit();
        } catch (Throwable $e) {
            $this->model->rollback();
            $this->error($e->getMessage());
        }
        if ($result == false) {
            $this->error(__('No rows updated'));
        }
    }
    /**
     * 若需重写查看、编辑、删除等方法，请复制 @see \app\admin\library\traits\Backend 中对应的方法至此进行重写
     */
}